# from __future__ import absolute_import, unicode_literals

import os

from celery import Celery, shared_task

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'recruitment.settings.base')

app = Celery('recruitment')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django apps.
app.autodiscover_tasks()


@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')


@app.task
def test(arg):
    print(arg)


# @app.task
# def add(x, y):
#     z = x + y
#     print(z)

# 管理定时任务的4种方法

# ①系统启动时自动注册定时任务
from celery.schedules import crontab


@app.on_after_configure.connect  # django信号
def setup_periodic_tasks(sender, **kwargs):
    # Calls test('hello') every 10 seconds.
    sender.add_periodic_task(100.0, test.s('-----1111------1111'), name='①系统启动时自动注册定时任务 print')

    # Calls test('world') every 30 seconds
    # sender.add_periodic_task(30.0, test.s('world'), expires=10)

    # Executes every Monday morning at 7:30 a.m.
    sender.add_periodic_task(
        crontab(hour=7, minute=30, day_of_week=1),
        test.s('Happy Mondays!'),
    )


# ②在 Admin 后台添加管理定时任务

# ③直接设置应用的 beat_schedule
# 注意下面的tasks.add方法，必须显式import,才能正确注册
from recruitment.tasks import add

app.conf.beat_schedule = {
    '③直接设置应用的 beat_schedule:plus/100s': {
        'task': 'recruitment.tasks.add',
        # 'task': 'add',
        'schedule': 100.0,
        'args': ('-----3333------3333',)
    },
}

# ④运行时添加定时任务(需要在django,beat,celery,flower依次运行后,再补上需要运行的定时任务(且不能出现同名task,会包重名错误)，否则出现Apps aren't loaded yet问题)
# import json
# from django_celery_beat.models import PeriodicTask,IntervalSchedule
# # 先创建定时策略
# schedule, created = IntervalSchedule.objects.get_or_create(every=10,period=IntervalSchedule.SECONDS,)
# # 再创建任务
#
# task = PeriodicTask.objects.create(interval=schedule, name='----④运行时添加定时任务',
#                                        task= 'recruitment.celery.test', args=json.dumps(['-----4444------44444'] ),)
# #
# app.conf.timezone = "Asia/Shanghai"
